import { JSWebrtc } from "@/global-utils/webrtc/index.js";
import ZLMRTCClient from "@/global-assets/webrtc/ZLMRTCClient.js";

/**
 *	流媒体播放切换
 * @param option videoDomId:视频播放dom的id , videoUrl:视频播放地址
 * @param fn  回调函数 play: webRtc播放实例 , videoStatus:视频播放状态 0 等待 1成功 2失败
 */
export const videoPlay = (
  option: { videoDomId: string; videoUrl: any },
  fn: (play: any, videoStatus: number) => void
): any => {
  let play: any;
  const inOrOutNetwork = window.localStorage.getItem("inOrOutNetwork") || "0";
  nextTick(() => {
    const theVideo = document.getElementById(option.videoDomId);
    if (inOrOutNetwork === "0") {
      play = new JSWebrtc.Player(option.videoUrl, {
        video: theVideo,
        autoplay: true,
        onPlay: (): void => {
          fn(play, 1);
        },
      });
      fn(play, 0);
    } else {
      play = new ZLMRTCClient.Endpoint({
        element: theVideo, // video 标签
        debug: true, // 是否打印日志
        zlmsdpUrl: `${option.videoUrl}&token=${window.sessionStorage.getItem(
          "token"
        )}`, //流地址
        simulecast: false, //是否启用 SimulCast 模式，SimulCast 用于将多个不同的编码质量级别同时传输到远程端点
        useCamera: false, //是否启用摄像头
        audioEnable: false, //是否启用音频
        videoEnable: false, //是否启用视频
        recvOnly: true, //是否仅接收数据流
      });
      fn(play, 0);
      play.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, () => {
        // ICE 协商出错
        fn(play, 2);
      });
      // 播放成功事件;
      play.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS, () => {
        fn(play, 1);
      });
      // 播放报错事件
      play.on(
        ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,
        (e: { code: number }) => {
          // offer anwser 交换失败
          console.error("offer anwser 交换失败", e);
          if (e.code === -400) {
            fn(play, 2);
          }
        }
      );
    }
  });
};

export const getVideoFirstFrame = async (videoUrl: any): Promise<string> => {
  // 创建video元素
  const video = document.createElement("video");
  video.src = videoUrl;
  video.setAttribute("crossOrigin", "Anonymous"); // 处理跨域
  video.setAttribute("preload", "auto"); // auto|metadata|none
  video.muted = true;
  video.autoplay = true;
  video.preload = "auto";
  // 等待视频加载完成
  // eslint-disable-next-line promise/avoid-new
  return new Promise((resolve, reject) => {
    video.addEventListener("loadedmetadata", () => {
      // 这里开始播放
      video.play();
      setTimeout(() => {
        // 过500ms 暂停， 解决空白问题
        video.pause();
        // 创建canvas元素
        const canvas = document.createElement("canvas");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 将视频帧绘制到canvas上
        const ctx = canvas.getContext("2d");
        ctx?.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 将canvas图像转换为base64格式的数据URI
        const dataUrl = canvas.toDataURL("image/png");
        // 返回base64格式的数据URI
        resolve(dataUrl);
      }, 500);
    });

    // 如果视频加载出错，则返回错误信息
    video.addEventListener("error", () => {
      reject(`Failed to load video: ${videoUrl}`);
    });
  });
};
